package com.lib.framework.network.adapter.request

import retrofit2.CallAdapter
import retrofit2.Response
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * Copyright (C), 2019-2020
 * FileName: Request2CallAdapterFactory
 * Author: Kevin
 * Date: 2020-01-06 17:47
 * Description: Request2CallAdapter 的 工厂类
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class Request2CallAdapterFactory: CallAdapter.Factory() {

    override fun get(
        returnType: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): CallAdapter<*, *>? {
        // 返回类型
        val rawType = getRawType(returnType)

        if (rawType != ApiRequest::class.java) {
            return null
        }

        if (returnType !is ParameterizedType) {
            throw IllegalStateException("ApiRequest return type must be parameterized" + " as ApiRequest<Foo> or ApiRequest<? extends Foo>")
        }

        val observableType = getParameterUpperBound(0, returnType)
        val rawObservableType = getRawType(observableType)
        val responseType = if (rawObservableType == Response::class.java) {
            check(observableType is ParameterizedType) {
                ("Response must be parameterized"
                        + " as Response<Foo> or Response<? extends Foo>")
            }

            getParameterUpperBound(0, observableType)
        } else {
           observableType
        }

        return Request2CallAdapter<Any>(responseType)
    }
}